package com.app.shell.view.mediators
{
	import com.app.common.GlobalConstants;
	import com.app.shell.message.ShellMessage;
	import com.app.shell.model.ActiveWidgetProxy;
	import com.app.shell.view.components.ControlPanelView;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.system.System;
	
	import mx.events.FlexEvent;
	
	public class ControlPanelMediator {
				
		[MessageDispatcher] public var dispatcher:Function;
		
		[Bindable] 
		public var view:ControlPanelView;
		
		[Inject]
		[Bindable] public var proxy:ActiveWidgetProxy;
		
		[Bindable] private var maxMemory:Number=0;
				
		[Observe]
		public function mediateView(view:ControlPanelView):void {
			trace("Mediator.mediateView() called");
			
			this.view = view;
			
			if (view != null) {
				if (view.initialized) {
					viewInitialized();
				} else {
					view.addEventListener(FlexEvent.CREATION_COMPLETE, componentInitialized);
				}
			}
		}
		
		protected function componentInitialized(e:Event = null):void {
			trace("Mediator.componentInitialized(): View fully initialized, safe to interact");
			viewInitialized();
		}
		
		public function viewInitialized():void {
			trace("Mediator.init(): Initializing view");
			view.homeButton.addEventListener(MouseEvent.CLICK, reactToHomeButton$Click);
			view.aboutButton.addEventListener(MouseEvent.CLICK, reactToAboutButton$Click);
			view.totalMemory.addEventListener(Event.RENDER, reactToTotalMemoryLabel$Render);
		}

		[Observe(phase="postDestroy")]
		public function viewDestroyed(view:ControlPanelView):void {
			view.homeButton.removeEventListener(MouseEvent.CLICK, reactToHomeButton$Click);
			view.aboutButton.removeEventListener(MouseEvent.CLICK, reactToAboutButton$Click);
			view.totalMemory.removeEventListener(Event.RENDER, reactToTotalMemoryLabel$Render);
		}		

		public function reactToHomeButton$Click(e:MouseEvent):void {
			trace("ControlPanelMediator: home button clicked");
			dispatcher(new ShellMessage(GlobalConstants.CREATE_WIDGET, GlobalConstants.MODULE_HOME));
		}
		
		public function reactToAboutButton$Click(e:MouseEvent):void {
			trace("ControlPanelMediator: about button clicked");
			dispatcher(new ShellMessage(GlobalConstants.CREATE_WIDGET, GlobalConstants.MODULE_ABOUT));
		}

		public function reactToTotalMemoryLabel$Render(e:Event):void {
			view.totalMemory.text = "Memory Used/Peak Memory : "+ memory;
		}

		private function get memory():String
		{
			System.gc();
			var mem:Number = Number(System.totalMemory / 1024 / 1024); 
			if(mem > maxMemory){
				maxMemory = mem;
			}
			
			return mem.toFixed(2) + " MB / "+maxMemory.toFixed(2)+"MB";
		}

	}
}